package com.whmskj.xjlhbc.mobile.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.CorpMember;
import com.whmskj.xjlhbc.domain.Js05dVarietyMaintenance;
import com.whmskj.xjlhbc.domain.ProgressInProductionOfBcsc05Orde;
import com.whmskj.xjlhbc.domain.ScProductionOrders;
import com.whmskj.xjlhbc.dto.OrderAddDto;
import com.whmskj.xjlhbc.dto.OrderUpdateDto;
import com.whmskj.xjlhbc.mapper.CorpMemberMapper;
import com.whmskj.xjlhbc.mapper.ProgressInProductionOfBcsc05OrdeMapper;
import com.whmskj.xjlhbc.mapper.ScProductionOrdersMapper;
import com.whmskj.xjlhbc.service.OrdersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.*;

@RestController
@Tag(name = "进度汇报",description = "进度汇报")
@RequestMapping("/jdhb")
public class JdhbController {

    @Autowired
    private ScProductionOrdersMapper scProductionOrdersMapper;

    @Autowired
    private ProgressInProductionOfBcsc05OrdeMapper pMapper;

    @Autowired
    private CorpMemberMapper corpMemberMapper;

    @Autowired
    private OrdersService ordersService;
    private final List<String> status = Arrays.asList("已接单", "生产中");

    /**
     * 统计所有订单以及订单状态的数量
     */
    @GetMapping("/top")
    @Operation(description = "统计")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult top(){
        // 查询所有订单
        List<ScProductionOrders> allOrders = scProductionOrdersMapper.selectList(new LambdaQueryWrapper<>());

        // 查询状态为"已接单"或"生产中"的订单
        LambdaQueryWrapper<ScProductionOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ScProductionOrders::getOrderStatus, status);
        List<ScProductionOrders> activeOrders = scProductionOrdersMapper.selectList(wrapper);

        LocalDate now = LocalDate.now();

        // 统计已接单或生产中的订单中已逾期的数量
        long overdueCount = activeOrders.stream().filter(f -> {
            try {
                LocalDate deliveryDate = LocalDate.parse(f.getDateOfDelivery());
                return now.isAfter(deliveryDate);
            } catch (Exception e) {
                return false;
            }
        }).count();

        Map<String, Long> map = new HashMap<>();
        map.put("all", (long) allOrders.size()); // 所有订单数量
        map.put("active", (long) activeOrders.size()); // 已接单或生产中订单数量
        map.put("overdue", overdueCount); // 已逾期订单数量

        return AjaxResult.success(map);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @Operation(description = "列表",parameters = @Parameter(name = "orderStatus",description = "订单状态"))
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, ScProductionOrders.class})
    ))
    public AjaxResult list(@RequestParam(required = false) String orderStatus){
        Page.startPage();
        LambdaQueryWrapper<ScProductionOrders> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(orderStatus)){
            wrapper.eq("已完成".equals(orderStatus),ScProductionOrders::getOrderStatus, orderStatus);
            wrapper.ne("未完成".equals(orderStatus),ScProductionOrders::getOrderStatus, "已完成");
            wrapper.eq(!"已完成".equals(orderStatus) && !"未完成".equals(orderStatus),ScProductionOrders::getOrderStatus, orderStatus);
        }
        wrapper.orderByDesc(ScProductionOrders::getId);
        List<ScProductionOrders> list = scProductionOrdersMapper.selectList(wrapper);
        list.forEach(item->{
            LambdaQueryWrapper<CorpMember> corpMemberWrapper = new LambdaQueryWrapper<>();
            corpMemberWrapper.eq(CorpMember::getMemberId, item.getModifyer());
            CorpMember corpMember = Optional.ofNullable(corpMemberMapper.selectOne(corpMemberWrapper)).orElseGet(CorpMember::new);
            item.setModifyer(corpMember.getNick());
        });
        return Page.getDataTable(list);
    }


    @GetMapping("/getInfo/{id}")
    @Operation(description = "详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, ScProductionOrders.class})
    ))
    public AjaxResult getInfo(@PathVariable("id") String id){
        ScProductionOrders scProductionOrders = scProductionOrdersMapper.selectById(id);
        String thePickupGuy = scProductionOrders.getThePickupGuy();
        String modifyer = scProductionOrders.getModifyer();
        Set<String> names = new HashSet<>();
        names.add(modifyer);
        names.add(thePickupGuy);
        LambdaQueryWrapper<CorpMember> corpMemberWrapper = new LambdaQueryWrapper<>();
        corpMemberWrapper.in(CorpMember::getMemberId, names);
        List<CorpMember> corpMembers = corpMemberMapper.selectList(corpMemberWrapper);
        CorpMember corpMember = corpMembers.stream().filter(filter -> filter.getMemberId().equals(modifyer)).findFirst().orElseGet(CorpMember::new);
        scProductionOrders.setModifyer(corpMember.getNick());
        corpMember = corpMembers.stream().filter(filter -> filter.getMemberId().equals(thePickupGuy)).findFirst().orElseGet(CorpMember::new);
        scProductionOrders.setThePickupGuy(corpMember.getNick());
        return AjaxResult.success(scProductionOrders);
    }

    @GetMapping("/jlList")
    @Operation(description = "进度汇报记录",parameters = @Parameter(name = "orderNumber",description = "订单编号"))
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class, ProgressInProductionOfBcsc05Orde.class})
    ))
    public AjaxResult jlList(@RequestParam(required = false) String orderNumber){
        Page.startPage();
        LambdaQueryWrapper<ProgressInProductionOfBcsc05Orde> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProgressInProductionOfBcsc05Orde::getOrderNumber, orderNumber);
        List<ProgressInProductionOfBcsc05Orde> list = pMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }

    @PostMapping("/save")
    @Operation(description = "进度汇报-保存")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    @Transactional
    public AjaxResult save(@RequestBody ProgressInProductionOfBcsc05Orde body){
        updateOrder(body);
        body.setReportingTime(new Date());
        int insert = pMapper.insert(body);
        if(insert>0)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    @PostMapping("/update")
    @Operation(description = "进度汇报-修改")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    @Transactional
    public AjaxResult update(@RequestBody ProgressInProductionOfBcsc05Orde body){
        updateOrder(body);
        int insert = pMapper.updateById(body);
        if(insert>0)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    private void updateOrder(ProgressInProductionOfBcsc05Orde body){
        String orderNumber = body.getOrderNumber();
        LambdaQueryWrapper<ScProductionOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScProductionOrders::getOrderNumber, orderNumber);
        ScProductionOrders scProductionOrders = scProductionOrdersMapper.selectOne(wrapper);
        scProductionOrders.setOrderStatus(body.getOrderStatus());
        scProductionOrders.setCompletionTime(new Date());
        scProductionOrders.setFulltimeStatus(body.getFulltimeStatus());
        scProductionOrders.setMaskStatus(body.getMaskStatus());
        scProductionOrders.setWeaving(body.getWroteState());
        scProductionOrdersMapper.updateById(scProductionOrders);
    }

    @GetMapping("/del/{id}")
    @Operation(description = "进度汇报-删除")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult del(@PathVariable("id") String id){
        int insert = pMapper.deleteById(id);
        if(insert>0)
            return AjaxResult.success();
        return AjaxResult.error();
    }

    /**
     * 品种列表
     * @param noNo3
     * @return
     */
    @GetMapping("/listVariety")
    public AjaxResult listVariety(@RequestParam(required = false) String noNo3) {
        return AjaxResult.success(ordersService.getVarietyList(noNo3));
    }

    /**
     * 生产中品种列表
     * @param noNo3
     * @return
     */
    @GetMapping("/listSczVariety")
    public AjaxResult listSczVariety(@RequestParam(required = false) String noNo3) {
        return AjaxResult.success(ordersService.listSczVariety(noNo3));
    }

    @GetMapping("/getVarietyById")
    public AjaxResult getVarietyById(@RequestParam String id) {
        Js05dVarietyMaintenance result = ordersService.getVarietyById(id);
        return AjaxResult.success(result);
    }

    @GetMapping("/getVarietyByNoNo3")
    public AjaxResult getVarietyByNoNo3(@RequestParam String noNo3) {
        Js05dVarietyMaintenance result = ordersService.getVarietyByNoNo3(noNo3);
        return AjaxResult.success(result);
    }

    /**
     * 新增订单
     */
    @PostMapping("/addOrder")
    @Operation(description = "新增订单")
    public AjaxResult addOrder(@Valid @RequestBody OrderAddDto request) {
        return ordersService.addOrder(request);
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/delete/{orderNumber}")
    @Operation(description = "删除订单")
    public AjaxResult deleteOrder(@PathVariable String orderNumber) {
        return ordersService.deleteByOrderNumber(orderNumber);
    }

    /**
     * 修改订单
     */
    @PutMapping("/update")
    public AjaxResult updateOrder(@Valid @RequestBody OrderUpdateDto updateDto) {
        return ordersService.updateOrder(updateDto);
    }

    /**
     * 根据ID查询订单
     */
    @GetMapping("/{orderNumber}")
    public AjaxResult getOrder(@PathVariable String orderNumber) {
        LambdaQueryWrapper<ScProductionOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScProductionOrders::getOrderNumber, orderNumber).last("limit 1");
        ScProductionOrders scProductionOrders = scProductionOrdersMapper.selectOne(wrapper);
        if(Objects.nonNull(scProductionOrders)){
            return getInfo(scProductionOrders.getId());
        }
        return AjaxResult.success();
    }

    /**
     * 展示订单的所有数据（汇总和分月）
     */
    @GetMapping("/report")
    public AjaxResult getOrderReport() {
        return ordersService.getOrderReport();
    }




}
